<?php

use Illuminate\Support\Facades\Response;
use App\Services\ApiService;
/**
 * 接口数据返回json
 */
function ReturnMsg($code, $msg = '', $data = [])
{
    if (empty($code)) return '';
    $message = \App\Services\CommonService::getMEssage($code);
    $arr = array('status' => $code, 'msg' => $msg ? $msg : $message, 'data' => $data);
    return json_encode($arr, JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
}

/**
 * 接口数据返回json
 */
function DockingReturnMsg($code, $msg = '', $data = [])
{
    if (empty($code)) return '';
    $message = \App\Services\CommonService::getMEssage($code);
    $arr = array('code' => $code, 'msg' => $msg ? $msg : $message, 'data' => $data);
    return Response::json($arr);
}

/**
 * 接口数据返回json
 */
function OutputReturnMsg($code, $msg = '', $data = [])
{
    if (empty($code)) return '';
    $message = \App\Services\CommonService::getMEssage($code);
    $arr = array('status' => $code, 'msg' => $msg ? $msg : $message, 'data' => $data);
    return Response::json($arr);
}

/**
 * 获取真实IP地址
 */
function getRealIp()
{
    $ip = false;
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
        $ip = getenv("HTTP_CLIENT_IP");
    } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
        $ips = explode(", ", getenv("HTTP_X_FORWARDED_FOR"));
        if ($ip) {
            array_unshift($ips, $ip);
            $ip = false;
        }
        $ipscount = count($ips);
        for ($i = 0; $i < $ipscount; $i++) {
            if (!preg_match("/^(10|172\.16|192\.168)\./i", $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
        $ip = getenv("REMOTE_ADDR");
    } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
        $ip = $_SERVER['REMOTE_ADDR'];
    } else {
        $ip = "unknown";
    }
    return isIp($ip) ? $ip : "unknown";
}

// 身份证号计算年龄
function getAgeByID($id)
{

    //过了这年的生日才算多了1周岁
    if (empty($id)) return '无';
    $date = strtotime(substr($id, 6, 8));
    //获得出生年月日的时间戳
    $today = strtotime('today');
    //获得今日的时间戳
    $diff = floor(($today - $date) / 86400 / 365);
    //得到两个日期相差的大体年数

    //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
    $age = strtotime(substr($id, 6, 8) . ' +' . $diff . 'years') > $today ? ($diff + 1) : $diff;

    return $age;
}

function getCityByIP()
{
    $ip = getRealIp();
    $url = "https://restapi.amap.com/v3/ip?ip={$ip}&key=d48c6ce64a8c5277b9166f38db246e34";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);

    if (isset($data['city'])) {
        return $data['city'] ? $data['province'] . $data['city'] : '';
    } else {
        return isset($data['province']) ? $data['province'] : $ip;
    }
}
/**
 * 检查是否是合法的IP
 */
function isIp($ip)
{
    if (preg_match('/^((\d|[1-9]\d|2[0-4]\d|25[0-5]|1\d\d)(?:\.(\d|[1-9]\d|2[0-4]\d|25[0-5]|1\d\d)){3})$/', $ip)) {
        return true;
    } else {
        return false;
    }
}

function createToken($key = '')
{
    return md5($key . rand(100000, 999999) . $_SERVER['REQUEST_TIME']);
}

function dateFormat($time)
{
    return $time ? date('Y-m-d H:i:s', $time) : '';
}

function dateDFormat($time)
{
    return $time ? date('Y-m-d', $time) : '';
}

//调用这个函数，将其幻化为数组，然后取出对应值
function object_array($array)
{
    if (is_object($array)) {
        $array = (array)$array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

//无限极分类
function generateTree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = 0)
{
    $tree = array();
    $packData = array();
    foreach ($list as $data) {
        $packData[$data[$pk]] = $data;
    }
    foreach ($packData as $key => $val) {
        if ($val[$pid] == $root) {
            //代表跟节点, 重点一
            $tree[] = &$packData[$key];
        } else {
            //找到其父类,重点二
            $packData[$val[$pid]][$child][] = &$packData[$key];
        }
    }
    return $tree;
}

//不进行四舍五入并保留两位小数
function format_number($data, $precision = 2)
{
    if (is_numeric($data)) {
        if (is_float($data)) {
            $data_arr = explode('.', $data);
            $data = $data_arr[0] . '.' . substr($data_arr[1], 0, 4);
        } else {
            $precision = 0;
        }
        return number_format($data, $precision, '.', '');
    }

    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $data[$key] = fix_number_precision($value, $precision);
        }
        return $data;
    }
    return $data;
}


//筛选时间查询
function searchTime($time)
{
    $timeArr = explode('~', $time);
    $begin_time = trim($timeArr[0]);
    $end_time = trim($timeArr[1]);
    if (strpos($begin_time, '-') === false) { //按年 如2020 ~ 2020查2020年  2020 ~ 2021查2020年和2021年
        $timeArr['begin_time'] = $begin_time . '-01-01 00:00:00';
        $timeArr['end_time'] = $end_time . '-12-31 23:59:59';
    } elseif (strlen($begin_time) == 7) { //按月 如2021-02 ~ 2021-02查2月  2021-02 ~ 2021-03查2月和3月
        $timeArr['begin_time'] = $begin_time . '-01';
        $firstday = date('Y-m-01', strtotime($end_time));
        $timeArr['end_time'] = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
    } else {
        $timeArr['begin_time'] = $begin_time;
        $timeArr['end_time'] = $end_time;
    }
    return $timeArr;
}

/**
 * curl get
 * @param $url
 * @param $params
 * @param bool $isEncode
 * @return mixed
 */
function http_get($url, $params, $isEncode = true)
{
    if(!empty($params)){
        $params = http_build_query($params);
        if (!$isEncode) {
            $params = urldecode($params);
        }
        $url = $url . "?" . $params;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 2);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}


/**
 * curl post
 * @param $url
 * @param $params
 * @param null $header
 * @param bool $isHttps
 * @param int $curlTimeOut
 * @return mixed
 */
function http_post($url, $params, $header = null, $isHttps = false, $curlTimeOut = 20)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, $curlTimeOut);
    if (is_array($params)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    } else {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    }
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    if (!is_null($header)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    if ($isHttps == true) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    }
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

/**
 * PHP发送Json对象数据
 * @param $url 请求url
 * @param $jsonStr 发送的json字符串
 * @return array
 */
function http_post_json($url, $jsonStr)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json;',
            'Content-Length: ' . strlen($jsonStr)
        )
    );
    $response = curl_exec($ch);
    var_dump($response);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return array($httpCode, $response);
}



//格式化分页数据
function formatPage($data)
{
    //删除分页多余信息
    unset($data['first_page_url']);
    unset($data['from']);
    unset($data['last_page_url']);
    unset($data['links']);
    unset($data['next_page_url']);
    unset($data['path']);
    unset($data['prev_page_url']);
    unset($data['to']);
    return $data;
}

//验证手机号是否正确
function Verify_Phone($mobile)
{
    /**
     * 移动：134、135、136、137、138、139、150、151、152、157、158、159、182、183、184、187、188、178(4G)、147(上网卡);
     * 联通：130、131、132、155、156、185、186、176(4G)、145(上网卡);
     * 电信：133、153、180、181、189 、177(4G);
     * 卫星通信：1349;
     * 虚拟运营商：170;
     * 130、131、132、133、134、135、136、137、138、139
     * 145、147
     * 150、151、152、153、155、156、157、158、159
     * 170、176、177、178
     * 180、181、182、183、184、185、186、187、188、189
     */
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('/^1[3456789]\d{9}$/', $mobile) ? true : false;
}

//验证手机号和固定电话是否正确
function isTel($tel)
{
    $isMob = "/^1[3456789]{1}\d{9}$/";
    $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
    $is400 = "/^400(-\d{3,4}){2}$/";
    $is4001 = "/^400(\d{3,4}){2}$/";
    if (!preg_match($isMob, $tel) && !preg_match($isTel, $tel) && !preg_match($is400, $tel) && !preg_match($is4001, $tel)) {
        return false;
    } else {
        return true;
    }
}

//验证邮箱是否正确
function check_email($email)
{
    if (filter_var($email, FILTER_VALIDATE_EMAIL) !== false) { //先用PHP内置的一个变量过滤的方法验证email格式的有效性
        $email_arr = explode("@", $email);
        if (checkdnsrr(array_pop($email_arr), "MX")) { //再用checkdnsrr验证email的域名部分的有效性
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

//验证url地址是否正确
function check_url($url)
{
    if (preg_match('/^http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is', $url)) {
        return true;
    } else {
        return false;
    }
}

//验证工商注册号是否正确
function isBusinessRegistrationNumber($businessRegistrationNumber)
{
    return preg_match('/(^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$)|(^\d{15}$)/', $businessRegistrationNumber) ? true : false;
}

//验证身份证号是否正确
function check_passportid($id)
{
    //校验身份证位数和出生日期部分
    $pattern = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/";
    preg_match($pattern, $id, $match);
    $result = $match ? true : false;
    if (!$result) {
        return false;
    }
    //校验前两位是否是所有省份代码
    $province_code = ['11', '12', '13', '14', '15', '21', '22', '23', '31', '32', '33', '34', '35', '36', '37', '41', '42', '43', '44', '45', '46', '50', '51', '52', '53', '54', '61', '62', '63', '64', '65', '71', '81', '82', '91'];
    if (!in_array(substr($id, 0, 2), $province_code)) {
        return false;
    }
    //校验身份证最后一位
    $ahead17_char = substr($id, 0, 17);
    $last_char = substr($id, -1);
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); // 前17位的权重
    $c = array(1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2); //模11后的对应校验码
    $t_res = 0;
    for ($i = 0; $i < 17; $i++) {
        $t_res += intval($ahead17_char[$i]) * $factor[$i];
    }
    $calc_last_char = $c [$t_res % 11];
    if ($last_char != $calc_last_char) {
        return false;
    }
    return true;
}
/**
 *  根据身份证号码获取性别
 *  @param string $idcard    身份证号码
 *  @return int $sex 性别 1男 2女 0未知
 */
function get_sex($idcard) {
    if(empty($idcard)) return '';
    $sexint = (int) substr($idcard, 16, 1);
    return $sexint % 2 === 0 ? '女' : '男';
}

//验证支付宝账号是否正确
function check_alipayaccount($alipayaccount)
{
    return preg_match('/^(?:1[3-9]\d{9}|[a-zA-Z\d._-]*\@[a-zA-Z\d.-]{1,10}\.[a-zA-Z\d]{1,20})$/', $alipayaccount) ? true : false;
}

function getValue($key, $arr)
{
    if (array_key_exists($key, $arr)) {
        return $arr[$key];
    } else {
        return '';
    }
}

/**
 * 元转毫
 * @param $yuan
 * @return int
 */
function toHao($yuan)
{
    return intval(round($yuan * 10000, 0));
}

/**
 * 元转分
 * @param $yuan
 * @return int
 */
function toFen($yuan)
{
    return intval(round($yuan * 100, 0));
}

/**
 * 分转元
 * @param $yuan
 * @return int
 */
function toYuanBYFen($fen)
{
    return sprintf("%.4f",$fen / 100);
}

/**
 * 支付宝服务费
 * @param $yuan
 * @return false|float
 */
function toServiceCharge($yuan)
{
    return round($yuan * 0.006, 2);
}

/**
 * 对象转数组
 * @param $data
 * @return array
 */
function obToArray($ob)
{
    if ((!is_array($ob) && !is_object($ob)) || empty($ob)) return [];
    return json_decode(json_encode($ob), true);
}

//按天租赁转期数
function DayToPeriods($day)
{
    if ($day <= 30) {
        $periods = 1;
    } else {
        $periods = floor($day / 30);
    }
    return $periods;
}

//下单获取租期开始时间结束时间
function GetRentTime($lease_set, $start_date, $lease_time)
{
    $data = [];
    $lease_time = $lease_time - 1;
    if ($lease_set == 1) {//按月
        $begin_time = time() + $start_date * 24 * 3600;
        $data['end_date'] = date("Y.m.d", strtotime("+$lease_time month", $begin_time));
        $data['begin_date'] = date("Y.m.d", $begin_time);
    } elseif ($lease_set == 2) {//按天
        $time = time();
        $begin_time = $time + $start_date * 24 * 3600;
        $data['end_date'] = date("Y.m.d", strtotime("+$lease_time day", $begin_time));
        $data['begin_date'] = date("Y.m.d", $begin_time);
    } elseif ($lease_set == 3) {//自定义租期
        $time = time();
        $begin_time = $time + $start_date * 24 * 3600;
        $data['end_date'] = date("Y.m.d", strtotime("+$lease_time day", $begin_time));
        $data['begin_date'] = date("Y.m.d", $begin_time);
    }
    return $data;
}

/**
 * 接口校验
 * @param $allData
 * @param $crypt
 * @param $key
 * @return bool
 */
function apiVerify($allData, $crypt, $key)
{
    $flag = false;
    foreach ($allData as $k => &$item) {
        if(is_array($item)){
            foreach ($item as $kk => &$item1){
                if(is_array($item1)){
                    foreach ($item1 as $kk1 => &$item11){
                        if (is_null($item11)) {
                            $item11 = "";
                        }
                    }
                }else{
                    if (is_null($item1)) {
                        $item1 = "";
                    }
                }
            }
        }
        if (is_null($item)) {
            $item = "";
        }
    }
    if ($crypt == md5(json_encode($allData, JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES) . $key)) {
        $flag = true;
    }
    return $flag;
}

//构造分页
function newPage($page = 1, $limit = 10)
{
    $data = [];
    $page = !empty($page) ? $page - 1 : 0;
    $limit = !empty($limit) ? $limit : 10;
    $data['page'] = ($page) * $limit;
    $data['limit'] = $limit;
    return $data;
}

//8位字符串邀请码
function randString()
{
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0, 25)]
        . strtoupper(dechex(date('m')))
        . date('d') . substr(time(), -5)
        . substr(microtime(), 2, 5)
        . sprintf('%02d', rand(0, 99));
    for (
        $a = md5($rand, true),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
        $d = '',
        $f = 0;
        $f < 8;
        $g = ord($a[$f]),
        $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
        $f++
    ) ;
    return $d;
}

//随机生成纯数字
function invitation_no()
{
    return substr(date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8), 4, 16);
}

/**
 * 计算账单优惠金额
 * @param $leaseTotal array 账单金额【‘租期ID’=》账单金额】
 * @param $receiptAmount int 实付总金额
 * @return mixed
 */
function computeDiscount($leaseTotal, $receiptAmount)
{
    if ($leaseTotal) {
        //账单总金额
        $totalAmount = array_sum($leaseTotal);
        $discount = $totalAmount - $receiptAmount;

        if ($discount <= $totalAmount) {
            foreach ($leaseTotal as $k => $item) {
                $res = $item - $discount;
                if ($res > 0) {
                    $leaseTotal[$k] = $res;
                    $res = 0;
                } else {
                    $leaseTotal[$k] = 0;
                }
                $discount = abs($res);
            }
        }
    }
    return $leaseTotal;
}

/**
 * 多维数组去重
 * @param $arr
 * @param $key
 * @return mixed
 */
function assoc_unique($arr, $key)
{
    $tmp_arr = array();
    foreach ($arr as $k => $v) {
        if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            unset($arr[$k]);
        } else {
            $tmp_arr[] = $v[$key];
        }
    }
    sort($arr); //sort函数对数组进行排序
    return $arr;
}

/**
 * 生成单号
 * @return string
 */
function createNo()
{
    return date('YmdHis') . mt_rand(10000000, 99999999);
}

/**
 * 返回相差的月份数量
 * @param $date1 string 开始日期
 * @param $date2 string 结束日期
 * @return float|int
 */
function getMonthNum($date1, $date2)
{
    $date1_stamp = strtotime($date1);
    $date2_stamp = strtotime($date2);
    list($date_1['y'], $date_1['m'], $date_1['d']) = explode("-", date('Y-m-d', $date1_stamp));
    list($date_2['y'], $date_2['m'], $date_2['d']) = explode("-", date('Y-m-d', $date2_stamp));
    if ($date_2['d'] > $date_1['d']) {
        $ceil_num = 1;
    } else {
        $ceil_num = 0;
    }
    return abs($date_1['y'] - $date_2['y']) * 12 + $date_2['m'] - $date_1['m'] + $ceil_num;
}

/**
 * URL安全的字符串base64编码
 * @param $string
 * @return array|string|string[]
 */
function base64_urlsafe_encode($string)
{
    $data = base64_encode($string);

    return str_replace(array('+', '/', '='), array('-', '_', ''), $data);
}

/**
 * URL安全的字符串base64解码
 * @param $string
 * @return false|string
 */
function base64_urlsafe_decode($string)
{
    $data = str_replace(array('-', '_'), array('+', '/'), $string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }

    return base64_decode($data);
}

function FetchRepeatMemberInArray($array) {
    $len = count($array);
    $repeat_arr = [];
    for($i = 0; $i < $len; $i ++) {
        for($j = $i + 1; $j < $len; $j ++) {
            if ($array [$i] == $array [$j]) {
                $repeat_arr [] = $array [$i];
                break;
            }
        }
    }
    return $repeat_arr;
}

/**
 * 收货地址省市县重复去除
 */
function AddressRemoveRepeat($prov,$city,$area,$address){
    if(empty($prov) || empty($city) || empty($area) || empty($address)){
        return $address;
    }
    if(strpos($address,$area) !== false){
        $address = str_replace($area,'',$address);
    }
    if(strpos($address,$city) !== false){
        $address = str_replace($city,'',$address);
    }
    if(strpos($address,$prov) !== false){
        $address = str_replace($prov,'',$address);
    }
    if(strpos($address,'---') !== false){
        $address = str_replace('---','',$address);
    }
    return $address;
}

/**
 * 获取网络图片的Base64编码
 * $img_url 网络图片地址
 * $hasPre  是否有前缀
 * @return string
 */
 function imgToBase64($img_url,$hasPre = true)
{
    $img_base64 = '';
    $imageInfo = getimagesize($img_url);
    if (!$imageInfo) {
        return false;
    }
    $img_base64 =  chunk_split(base64_encode(file_get_contents($img_url)));
//    if ($hasPre) {
//        $img_base64 = 'data:' . $imageInfo['mime'] . ';base64,'.$img_base64;
//    }
    return $img_base64;
}



DiffDate("2021-01-06","2023-06-16");


// 计算两个日期相差 年 月 日
function DiffDate($date1, $date2) {
    if (strtotime($date1) > strtotime($date2)) {
        $ymd = $date2;
        $date2 = $date1;
        $date1 = $ymd;
    }
    list($y1, $m1, $d1) = explode('-', $date1);
    list($y2, $m2, $d2) = explode('-', $date2);
    $y = $m = $d = $_m = 0;
    $math = ($y2 - $y1) * 12 + $m2 - $m1; //相差总月数
    $y = round($math / 12);  //相差年数
    $m = intval($math % 12);  //相差月数
    $mm = $math; //相差总月数
    $d = (mktime(0, 0, 0, $m2, $d2, $y2) - mktime(0, 0, 0, $m2, $d1, $y2)) / 86400;
    if ($d < 0) {
        $m -= 1;
        $d += date('j', mktime(0, 0, 0, $m2, 0, $y2));
    }
    $m < 0 && $y -= 1;
    return array($y, $m, $d,$mm);
}

/**
 * 导出csv
 * @param array $data 导出的数据
 * @param array $headList 头部文字描述
 * @param string $fileName 文件名
 */
function csvExporta($data, $headList, $fileName)
{
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
    header('Cache-Control: max-age=0');

    $fp = fopen('php://output', 'a');
    foreach ($headList as $key => $value) {
        $headList[$key] = iconv('utf-8', 'gbk', $value);
    }

    fputcsv($fp, $headList);
    $num = 0;
    $limit = 100000;

    $count = count($data);
    for ($i = 0; $i < $count; $i++) {
        $num++;
        if ($limit == $num) {
            ob_flush();
            flush();
            $num = 0;
        }
        $row = $data[$i];
        foreach ($row as $key => $value) {
            $row[$key] = iconv('utf-8', 'gbk', $value);
        }
        fputcsv($fp, $row);
    }
}


/**
 * csv_get_lines 读取CSV文件中的某几行数据
 * @param $csvfile csv文件路径
 * @param $lines 读取行数
 * @param $offset 起始行数
 * @return array
 * */
function parseFile($filename,$lineOne=false) {
    if (!$filename) {
        die("未选择文件");
    }
    $file = fopen($filename, 'r');
    $arr = [];
    $i=0;
    while ($line = fgets($file)) {
        $i++;
        if($i==1&&!$lineOne){
            continue;
        }
        $line = rtrim($line, "\n\r\0");
        $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
        if ($encoding != 'utf-8') {
            $line = mb_convert_encoding($line, 'utf-8', $encoding);
        }

        $arr[] = explode(',', $line);

    }
    return $arr;
}
/**
 * 导出csv
 * @param array $data 导出的数据
 * @param array $headList 头部文字描述
 * @param string $fileName 文件名
 */
function csvExport($data, $headList, $fileName)
{

    $exportdir =public_path('/export/');
    if(!is_dir($exportdir)) mkdir($exportdir);

    //生成csv文件
    $elsfile=$exportdir.$fileName.'.csv';
    $fp = fopen($elsfile, 'w');
    fputcsv($fp, $headList);
    //Windows下使用BOM来标记文本文件的编码方式
    fwrite($fp,chr(0xEF).chr(0xBB).chr(0xBF));
    foreach ($data as $line) {
        fputcsv($fp, $line);
    }
    fclose($fp);

    //zip
    $zipname='导出还款数据.zip';
    $zip_file_path=$exportdir.$zipname;
    $oZip = new ZipArchive();
    if($oZip->open($zip_file_path,ZipArchive::CREATE)==TRUE){
        $oZip->addFile($elsfile, $fileName.'.csv');
        $oZip->setEncryptionName($fileName.'.csv', ZipArchive::EM_AES_256);
        $oZip->setPassword('dlz123');
        $oZip->close();
        //下载链接
        $downfile="http://".$_SERVER['HTTP_HOST'].'/export/'.$zipname;
        return  header("Location: $downfile");
        return $downfile;
    }
    return false;

    $zipname='还款数据.zip';
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment;filename="' . $zipname );
    header('Cache-Control: max-age=0');
//    header('Content-Type: application/vnd.ms-excel');
//    header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
//    header('Cache-Control: max-age=0');

    $fp = fopen($fileName.'.csv');
//    $fp = fopen('php://output', 'a');
    foreach ($headList as $key => $value) {
        $headList[$key] = iconv('utf-8', 'gbk', $value);
    }

    fputcsv($fp, $headList);
    $num = 0;
    $limit = 100000;

    $count = count($data);
    for ($i = 0; $i < $count; $i++) {
        $num++;
        if ($limit == $num) {
            ob_flush();
            flush();
            $num = 0;
        }
        $row = $data[$i];
        foreach ($row as $key => $value) {
            $row[$key] = iconv('utf-8', 'gbk', $value);
        }
        fputcsv($fp, $row);
    }
    fclose($fp);
   $zipnames = fopen('php://output', 'a');

    $zip = new ZipArchive();
    $zip->open($zipname, ZipArchive::CREATE);


//    $zip->addFromString('aa.csv', stream_get_contents($fp));
//    $zip->close();
//      header('Content-Type: application/vnd.ms-excel');
//    header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
//    header('Cache-Control: max-age=0');

//    $password = "yourPassword";
//    if (!empty($password)) {
//        $zip->setEncryptionName("还款数据.csv", ZipArchive::EM_AES_256);
//        $zip->setPassword($password);
//    }
//    $zip->close();
//
//    header('Content-Length: ' . filesize($zipname));
//    header('Content-Type: application/zip');
//    header('Content-disposition: attachment; filename='.$zipname);
//    readfile($zipname);
//
//    // remove the zip archive
//    // you could also use the temp file method above for this.
//    unlink($zipname);
}


function to_post_labeila($path_url, $data)
{
    $domain ='https://b.labeilazulin.com';
    $token = 'c902ff87-519c-45ca-8456-e171a081bffb';

    $url = "{$domain}{$path_url}?token=".$token;

    unset($data['path_url']);

    ksort($data);
    $data["sign"] = strtoupper(md5(http_build_query($data) . "&token={$token}"));

    $data = is_array($data) ? json_encode($data, 256) : $data;
    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json",
            "content-type: application/json",
            "accept: */*",
        ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    \Illuminate\Support\Facades\Log::channel("otherlog")->debug('MDM 请求:', ['data'=>$data, 'err'=>$err, 'response'=>$response]);

    curl_close($curl);

    return json_decode($response, true);
}
